package cn.z2huo.knowledge.concurrency.producerconsumer;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * @author z2huo
 */
class Producer implements Runnable {

    /**
     * 生产时间间隔，生产一次等待的时间默认为 200 毫秒
     */
    private static final int PRODUCE_GAP = 200;

    /**
     * 总次数
     */
    static final AtomicInteger TURN = new AtomicInteger(1);

    /**
     * 生产者对象编号，从 1 号开始
     */
    static final AtomicInteger PRODUCER_NO = new AtomicInteger(1);

    /**
     * 生产者名称
     */
    private final String name;

    /**
     * 生产的动作
     */
    private final Callable<?> action;

    private int gap = PRODUCE_GAP;

    public Producer(Callable<?> action) {
        this(action, PRODUCE_GAP);
    }

    public Producer(Callable<?> action, int gap) {
        this.name = "生产者-" + PRODUCER_NO.getAndIncrement();
        this.action = action;
        this.gap = gap;
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 增加生产轮次
                TURN.getAndIncrement();
                System.out.println("生产者 " + name + " 生产开始");
                Object out = action.call();
                if (out != null) {
                    System.out.println("第 " + TURN.get() + " 轮生产，数据为 " + out);
                } else {
                    System.out.println("第 " + TURN.get() + " 轮生产，无数据");
                }
                ThreadUtil.sleep(gap, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
